package handle

import (
	"git.oschina.net/cnjack/z_app_server/tool"
	"github.com/martini-contrib/render"
	"net/http"
	"strconv"
	"time"
)

func MessageGetHandle(r render.Render, req *http.Request) {
	var err error
	var id, _ = strconv.Atoi(req.Header.Get("userid"))
	req.ParseForm()
	lastTime, err := messageTimeInfo.GetLastime(int64(id))
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if lastTime == 0 {
		lastTime = int(time.Now().Unix())
	}
	list, err := messageModel.GetList(lastTime, int64(id))
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	err = messageTimeInfo.Set(int64(id), int(time.Now().Unix()))
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	var data = make(map[string]interface{})
	var datalist = make(map[string]interface{})
	for i, v := range list {
		datalist[strconv.Itoa(int(i))] = tool.Struct2Map(v)
	}
	data["list"] = datalist
	data["code"] = "0"
	data["lasttime"] = lastTime
	r.JSON(200, data)
}
func MessageSendHandle(r render.Render, req *http.Request) {
	var err error
	req.ParseForm()
	var v_timeStr = req.PostFormValue("v_time")
	if v_timeStr == "" {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "param is empty",
		})
		return
	}
	v_time, err := strconv.Atoi(v_timeStr)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	var id, _ = strconv.Atoi(req.Header.Get("userid"))
	CpInfo, err := relationModel.FindCp(int64(id))
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if CpInfo == nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "you have not cp",
		})
		return
	}

	err = messageModel.AddOne(int64(id), CpInfo.Id, v_time)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	r.JSON(200, map[string]interface{}{
		"code": "0",
		"info": "",
	})
}
